var EventProxy = require('eventproxy');

var mongoose = require('./db.js');
var User = require('./user.js');
var Comment = require('./comment.js');

var postSchema = mongoose.Schema({
	userName: {
		type: String,
		require: true
	},
	content: {
		type: String,
		require: true
	},
    tags: {
        type: Array,
        require: false
    },
	anonymous: {
		type: String,
		require: true
	},
	good: {
		type: Number,
        require:false
	},
	time: {
		type: String,
		require: true
	}
});

var Post = mongoose.model('Post', postSchema);

var postDAO = function(){};

//发表
postDAO.prototype.add = function(post, userName, callback){
	var p = new Post(post);
	p.good = 0; // 初始化赞为0
	p.userName = userName;
	p.time = (new Date()).valueOf(); //发布时间
	if(!post.anonymous){
		p.anonymous = false;
	}
	if(post.tags){
        p.tags = post.tags.split(" ");
    }
	p.save(function(e){
		callback(e);
	});
};

//随机查询
postDAO.prototype.getPostByRandom = function (callback) {
	Post.count({}, function (e, count) {
		if(e){
			return callback(e);
		} else {
            if(count == 0){
                return callback('还没有人发布过秘密哦~');
            }
			var n = Math.floor(count*Math.random());

			Post.find().skip(n).limit(1).lean().exec(function (e, post){
                var p = post[0];
                var ep = new EventProxy();

                ep.all('find_author', 'count_comments', function(){
                    callback('', p);
                });

                if(p.anonymous == 'false'){
                    User.findUserByName(p.userName, function (e ,user) {
                        p.author = user;
                        ep.emit('find_author');
                    });
                } else {
                    //匿名则直接返回，不要作者信息
                    ep.emit('find_author');
                }

                Comment.countByPostId(p._id, function (e, count){
                    if(e){
                        console.log('Post Comment not found , Error: ' , e);
                    } else {
                        p.comments = count;
                    }
                    ep.emit('count_comments');
                });

            });
		}
	});
};

//分页查询
postDAO.prototype.findByPage = function(start, pageNumber, hot, tag, callback){
    var sortBy = {'time': -1};
    var query = {};
    //如果是标签查询
    if(tag){
        query = {tags: tag};
    }
    //如果是查询最热的秘密
    if(hot){
        sortBy = {good: -1};
    }
	Post.find(query).sort(sortBy).skip(start).limit(pageNumber).lean().exec(function (e, posts){
		var length = posts.length;

		var ep = new EventProxy();
		ep.all('author_find_complete', 'comments_count_complete', function (){
			callback(posts);
		});

		ep.after('author_find', length, function (){
			ep.emit('author_find_complete');
		});

		ep.after('comments_count', length, function(){
			ep.emit('comments_count_complete');
		});
		
		if(e){
			return callback(null, e);
		} else {
			
			for(var i=0; i<length; i++){

				(function(j){
					//查询出发布者的信息
                    if(posts[j].anonymous == 'false'){
                        User.findUserByName(posts[j].userName, function (e, user){
                            if(e){
                                console.log('Post Author not found , Error:' + e);
                            } else {
                                posts[j].author = user;
                            }
                            ep.emit('author_find');
                        });
                    } else {
                        ep.emit('author_find');
                    }

					//查询出有多少条评论
					Comment.countByPostId(posts[j]._id, function (e, count){
						if(e){
                            console.log('Post Comment not found , Error: ' , e);
						} else {
							posts[j].comments = count;
						}
                        ep.emit('comments_count');
					});
				})(i);
			}
		}
	});
};

//通过用户id查找
postDAO.prototype.findByUserName = function (userName, start, pageNumber, callback){

	Post.find({userName: userName, anonymous: false}).sort({'time': -1}).skip(start).limit(pageNumber).lean()
		.exec(function (e, posts){
			if(e){
				return callback(null, e);
			}
			var length = posts.length;
			var ep = new EventProxy();

			ep.after('comments_count', length, function (){
				callback(posts);
			});

			for(var i=0; i<length; i++){
				(function(j){
					//查询出有多少条评论
					Comment.countByPostId(posts[j]._id, function (e, count){
						if(e){
                            console.log('Post Comment not found , Error: ' , e);
						} else {
							posts[j].comments = count;
						}
                        ep.emit('comments_count');
					});

				})(i);
			}
		});
};

//点赞
postDAO.prototype.vote = function(cid, vote){
	Post.update({_id: cid}, {good: vote + 1}, function(e, effectedNumber){
		if(effectedNumber != 1){
			console.log('粗大事了！点一个赞改了不止一个记录了！');
		}
	});
};
//更新
postDAO.prototype.updatePostById = function (post, callback) {
    if(!post.anonymous){
        post.anonymous = false;
    }
    Post.update({_id: post.postId}, {$set: {content: post.content, anonymous: post.anonymous}}, {}, callback);
};
//删除
postDAO.prototype.deletePostById = function(id, callback){
	Post.remove({_id: id}, callback);
};

//根据内容查找
postDAO.prototype.searchPost = function (key, callback) {
    Post.find({content: new RegExp(key)}, callback);
};

//根据ID查找
postDAO.prototype.findByPostId = function (id, callback) {
    Post.findOne({_id: id}).lean().exec(function (err, post) {
        if(err) {
            console.log(err);
            return callback('',null);
        } else {
            var ep = new EventProxy();
            ep.all('author_find', 'comments_count', function () {
                callback('', post);
            });

            User.findUserByName(post.userName, function (e, user){
                if(e){
                    console.log('Post Author not found , Error:' + e);
                } else {
                    post.author = user;
                }
                ep.emit('author_find');
            });

            Comment.countByPostId(post._id, function (e, count){
                if(e){
                    console.log('Post Comment not found , Error: ' , e);
                } else {
                    post.comments = count;
                }
                ep.emit('comments_count');
            });
        }
    });
};

postDAO.prototype.getPostsCount = function(callback){
    Post.count(callback);
}

postDAO.prototype.deletePostByUserName = function(userName, callback){
    Post.remove({userName: userName}, callback);
};

module.exports = new postDAO();